<template>
  <div>
    <el-row class="commonPage">
      <el-col class="set-max-height">
        <div class="search">
          <div class="option-btns">
            <el-input v-model="search.menuName" v-haspermi="['bxy:menu:search']" placeholder="请输入菜单名称" class="search-title" clearable style="width:200px" />
            <el-button
              v-haspermi="['bxy:menu:search']"
              class="search-button"
              type="primary"
              @click="onSearch()"
            >
              {{ $t('notice.search') }}
            </el-button>
            <el-button v-haspermi="['bxy:menu:search']" type="primary" @click="setMenuSearch()">重置</el-button>
            <div style="float:right">
              <el-button v-haspermi="['bxy:menu:add']" class="search-button" type="primary" @click="add()">新增</el-button>
            </div>
          </div>
        </div>
        <div class="notice-content">
          <el-table
            size="small"
            :data="treeList"
            :default-sort="{prop: 'orderNum', order: 'ascending'}"
            row-key="menuId"
            lazy
            :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
          >
            <el-table-column prop="menuName" label="菜单名称" width="160" show-overflow-tooltip />
            <el-table-column prop="icon" label="图标" width="100">
              <template slot-scope="scope">
                <svg-icon :icon-class="scope.row.icon" />
              </template>
            </el-table-column>
            <el-table-column prop="orderNum" sortable label="排序" width="80" />
            <el-table-column prop="perms" label="权限标识" show-overflow-tooltip />
            <el-table-column prop="component" label="组件路径" show-overflow-tooltip />
            <el-table-column prop="visible" label="显示状态" width="150" :formatter="visibleLabel" align="center" />
            <el-table-column prop="status" label="菜单状态" width="100" :formatter="statusLabel" align="center" />
            <el-table-column prop="createTime" label="创建时间" align="center" width="200" />
            <el-table-column prop="orderNum" label="操作" align="center" width="160">
              <template slot-scope="scope">
                <el-button v-haspermi="['bxy:menu:edit']" size="mini" type="primary" plain @click="editMenu(scope.row)">编辑</el-button>
                <el-button v-haspermi="['bxy:menu:delete']" size="mini" type="danger" plain @click="del(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-col>
    </el-row>
    <el-dialog :title="title" :visible.sync="FormVisible" width="700px">
      <el-form
        ref="menuForm"
        :model="form"
        label-width="100px"
        :rules="rules"
      >
        <el-row>
          <el-col :span="24">
            <el-form-item label-width="" label="上级菜单">
              <el-select
                ref="selectReport"
                v-model="dictDataSelect"
                placeholder="请选择上级菜单"
                style="width:100%"
              >
                <el-option :label="dictDataSelect" :value="form.parentId" style="height:auto">
                  <el-tree
                    :data="menuOptions"
                    :props="patternProps"
                    @node-click="handleNodeClick"
                  />
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="菜单类型">
              <el-radio-group v-model="form.menuType">
                <el-radio label="M">目录</el-radio>
                <el-radio label="C">菜单</el-radio>
                <el-radio label="F">按钮</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item v-if="form.menuType != 'F'" label="菜单图标">
              <el-popover
                placement="bottom-start"
                width="470"
                @show="$refs['iconSelect'].reset()"
              >
                <IconSelect ref="iconSelect" @selected="selected" />
                <el-input slot="reference" v-model="this.form.icon" placeholder="请选择图标" readonly @focus="iconVisible = true" />
              </el-popover>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="名称" prop="menuName">
              <el-input v-model="form.menuName" placeholder="请输入名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排序" prop="orderNum">
              <el-input
                v-model="form.orderNum"
                type="number"
                placeholder="请输入排序码"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="form.menuType != 'F'" label="是否外链">
              <el-radio-group v-model="form.isFrame">
                <el-radio :label="0">是</el-radio>
                <el-radio :label="1">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col v-if="form.menuType != 'F'" :span="12">
            <el-form-item prop="path">
              <span slot="label">
                <span class="span-box">
                  <el-tooltip class="item" effect="dark" content="访问的路由地址，如：`ddio`或`/ddio`" placement="top">
                    <svg-icon icon-class="help" />
                  </el-tooltip>
                  <span> 路由地址 </span>
                </span>
              </span>
              <el-input v-model="form.path" placeholder="请输入路由地址" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="form.menuType == 'C'">
              <span slot="label">
                <span class="span-box">
                  <el-tooltip class="item" effect="dark" content="访问的组件路径，如：`ddio/department`，默认在`views`目录下" placement="top">
                    <svg-icon icon-class="help" />
                  </el-tooltip>
                  <span> 组件路径 </span>
                </span>
              </span>
              <el-input v-model="form.component" placeholder="请输入组件路径" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="form.menuType != 'M'">
              <span slot="label">
                <span class="span-box">
                  <el-tooltip class="item" effect="dark" content="权限字符，bxy:department:index" placement="top">
                    <svg-icon icon-class="help" />
                  </el-tooltip>
                  <span> 权限标识 </span>
                </span>
              </span>
              <el-input v-model="form.perms" placeholder="请输入权限标识" maxlength="50" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="form.menuType != 'F'" label="显示状态">
              <el-radio-group v-model="form.visible">
                <el-radio :label="0">显示</el-radio>
                <el-radio :label="1">隐藏</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="form.menuType != 'F'" label="菜单状态">
              <el-radio-group v-model="form.status">
                <el-radio :label="0">正常</el-radio>
                <el-radio :label="1">停用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="saveUser()">确 定</el-button>
        <el-button @click="FormVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import IconSelect from '@/components/IconSelect';
import menu from '@/api/menu';
export default {
  name: 'Menu',
  components: { IconSelect },
  data() {
    return {
      isShowTree: false,
      selectVisible: false,
      title: '新增菜单',
      iconVisible: false,
      list: [],
      FormVisible: false,
      type: 'add',
      showTree: false,
      menuOptions: [],
      dictDataSelect: null, /* 上级菜单的名字 */
      treeList: [],
      patternProps: {
        label: 'menuName',
        children: 'children',
      },
      form: {
        menuId: '',
        parentId: '',
        isFrame: 1,
        menuType: 'M', /* M 目录 C 菜单 F 按钮 */
        icon: '',
        menuName: '',
        orderNum: '',
        path: '',
        component: '',
        perms: '',
        visible: 0,
        status: 0,
      },
      search: {
        menuName: '',
      },
      rules: {
        menuName: [
          { required: true, message: '名称不能为空', trigger: 'blur',
          },
        ],
        orderNum: [
          { required: true, message: '顺序不能为空', trigger: 'blur',
          },
        ],
        path: [
          { required: true, message: '路由地址不能为空', trigger: 'blur',
          },
        ],
      },
    };
  },
  created() {
    this.getList();
    this.getTreeselect();
  },

  methods: {
    visibleLabel(row, column) {
      if (row.menuType == 'F') {
        return '';
      } else if (row.visible == '0') {
        return (<el-tag type='warning'  size='mini'>显示</el-tag>);
      } else {
        return (<el-tag type='info' size='mini'>隐藏</el-tag>);
      }
    },

    statusLabel(row, column) {
      if (row.menuType == 'F') {
        return '';
      } else if (row.status == '0') {
        return (<el-tag type='success' size='mini'>正常</el-tag>);
      } else {
        return (<el-tag type='info' size='mini'>停用</el-tag>);
      }
    },

    setMenuSearch() {
      this.search = {
        menuName: '',
      };
      this.getList();
    },

    async onSearch() {
      if (this.search.menuName) {
        const { data } = await menu.getMenuList(this.search);
        this.treeList = data.data;
      } else {
        this.getList();
      }
    },

    handleNodeClick(node) {
      this.dictDataSelect = node.menuName;
      if (node.menuid != 0) this.form.parentId = node.menuId;
      this.isShowTree = false;
    },

    async getList() {
      const { data } = await menu.getMenuList(this.search);
      this.list = data.data;
      this.treeList = this.treeData(data.data, 'parentId');
    },

    async getTreeselect() {
      const { data } = await menu.getMenuList();
      this.menuOptions = [];
      const menus = { menuId: 1, menuName: '主类目', children: [] };
      menus.children = this.treeData(data.data, 'parentId');
      this.menuOptions.push(menus);
    },

    updateNode(arr, node, key) {
      const childItems = arr.filter(item => item.parentId == node.menuId);
      if (childItems.length === 0) return;
      else {
        childItems.forEach(item => {
          this.updateNode(arr, item, key);
          node.children.push(item);
        });
      }
    },

    treeData(arr, key) {
      const result = [];
      arr.forEach(item => {
        if (item[key] == 1) {
          this.updateNode(arr, item, key);
          result.push(item);
        }
      });
      return result;
    },

    selected(name) {
      this.form.icon = name;
    },

    add() {
      this.title = '新增菜单';
      this.$refs.menuForm && this.$refs.menuForm.resetFields();
      this.dictDataSelect = '';
      this.type = 'add';
      this.FormVisible = true;
      this.form.menuId = '';
      this.form.parentId = 1;
      this.form.isFrame = 1;
      this.form.icon = '';
      this.form.menuName = '';
      this.form.orderNum = '';
      this.form.path = '';
      this.form.component = '';
      this.form.perms = '';
      this.dictDataSelect = '';
    },

    editMenu(row) {
      this.title = '修改菜单';
      this.$refs.menuForm && this.$refs.menuForm.resetFields();
      this.type = 'edit';
      this.FormVisible = true;
      this.form.menuId = row.menuId;
      this.form.parentId = row.parentId;
      this.form.isFrame = row.isFrame;
      this.form.menuType = row.menuType;
      this.form.icon = row.icon;
      this.form.menuName = row.menuName;
      this.form.orderNum = row.orderNum;
      this.form.path = row.path;
      this.form.component = row.component;
      this.form.perms = row.perms;
      this.form.visible = row.visible;
      this.form.status = row.status;
      this.dictDataSelect = row.parentId == 1 ? '主类目' : this.list.find(item => item.menuId == row.parentId).menuName;
    },

    async saveUser() {
      const obj = Object.assign({}, this.form);
      this.$refs['menuForm'].validate(async(valid) => {
        if (valid) {
          if (this.type === 'add') {
            const { data } = await menu.addMenu(obj);
            this.$message({
              message: data.msg,
              type: 'success',
            });
          } else {
            const { data } = await menu.editMenu(obj);
            this.$message({
              message: data.msg,
              type: 'success',
            });
          }
          this.FormVisible = false;
          this.getList();
          this.getTreeselect();
        }
      });
    },

    del(row) {
      this.$confirm('确认删除', '提示', {
        type: 'warning',
      }).then(async() => {
        await menu.delByMenuId(row.menuId);
        this.getList();
        this.getTreeselect();
      });
    },
  },
};
</script>
